package it.low.game.core.element;

import it.low.game.core.action.Action;
import it.low.game.core.element.activity.Targetable;
import it.low.game.core.location.MapPoint;

import java.util.HashMap;
import java.util.Map;


public class ActiveElement extends AreaElement implements Targetable {
	
	private long elementId = -1;
	
	public static final String ELEM_NAME = "ELEM_NAME";
	public static final String ELEM_IMAG = "ELEM_IMAG";
	
	public static final String MOV_SPEED = "MOV_SPEED";
	public static final String RUN_SPEED = "MOV_SPEED";
	public static final String SIG_RANGE = "SIG_RANGE";
	public static final String ATT_RANGE = "ATT_RANGE";
		
	private Map<String,String> attributes = new HashMap<String,String>();	
	private Map<String,Double> properties = new HashMap<String,Double>();
	
	private Map<Integer,Action> actions = new HashMap<Integer,Action>();
	private int maxPriority = 0;
	
	public ActiveElement(long id, String name, String img){
		this.elementId = id;
		this.setAttribute(ELEM_NAME, name);
		this.setAttribute(ELEM_IMAG, img);
	}
	
	public long getElementId(){
		return elementId;
	}
	
	public String getElementName(){
		return this.getAttribute(ELEM_NAME);
	}
	
	public boolean isInit(){
		return getMapPosition()!=null;
	}
	
	public boolean isDefaultAction(){
		return maxPriority<=0;
	}
	
	public void setNewAction(int priority, Action action){
		maxPriority = priority;
		actions.put(maxPriority, action);
	}
	
	public void startAction(int priority){
		maxPriority = priority;
		Action action = actions.get(maxPriority);
		action.start(this);
	}
	
	public void addNewAction(Action action){
		actions.put(++maxPriority, action);
	}
	
	public void startNewAction(Action action){
		actions.put(++maxPriority, action);
		action.start(this);		
	}
	
	public void executeActions(long elapsedTime){		
		Action action = actions.get(maxPriority);
		if(action!=null){
			if(excuteAction(action,elapsedTime)){				
				actions.remove(maxPriority--);
				if(maxPriority>=0){
					action = actions.get(maxPriority);
					action.resume(this);
				}
			}
		}
	}
	
	private boolean excuteAction(Action action, long elapsedTime){
		return action.run(this,elapsedTime);
	}
	
	public void setAttribute(String key, String value){
		attributes.put(key, value);
	}
	
	public String getAttribute(String key){
		return attributes.get(key);
	}
	
	public void setProperty(String key, double value){
		this.properties.put(key, value);
	}
	
	public double getProperty(String key){
		return this.properties.get(key);
	}
	
	public void setMapPosition(MapPoint mapPosition) {
		super.setMapPosition(mapPosition);
		state.setMapPosition(mapPosition);
	}
	
	public State getState(){
		return state;
	}
		
	public boolean equals(ActiveElement activeElement){
		return this.getElementId() == activeElement.getElementId();
	}
	
}
